package com.atguigu.flink.chapter07;

import com.atguigu.flink.bean.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/8/14 9:49
 */
public class Flink13_SideOut_2 {
    public static void main(String[] args) {
        OutputTag<String> alertTag30 = new OutputTag<String>("alert30"){};
        OutputTag<String> alertTag20 = new OutputTag<String>("alert20"){};
    
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        
        env.setParallelism(2);
        // 每隔5s计算这5s内的wordCount
        SingleOutputStreamOperator<String> main = env
            .socketTextStream("hadoop162", 9999)
            .map(new MapFunction<String, WaterSensor>() {
                @Override
                public WaterSensor map(String value) throws Exception {
                    String[] data = value.split(",");
                    return new WaterSensor(data[0], Long.valueOf(data[1]) * 1000, Integer.valueOf(data[2]));
                }
            })
        
            .keyBy(WaterSensor::getId)
            
            .process(new KeyedProcessFunction<String, WaterSensor, String>() {
                @Override
                public void processElement(WaterSensor value,
                                           Context ctx,
                                           Collector<String> out) throws Exception {
                    
                    if (value.getVc() > 30) {
                        // 把需要预警的数据写入到侧输出流
                        ctx.output(alertTag30, value.toString());
                    } else if (value.getVc() > 20) {
                        // 把需要预警的数据写入到侧输出流
                        ctx.output(alertTag20, value.toString());
                    } else {
                        out.collect(value.toString());
                    
                    }
                }
            });
        
        main.print("<20");
        main.getSideOutput(alertTag20).print(">20");
        main.getSideOutput(alertTag30).print(">30");
    
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
